const crypto = require('crypto');
const ResponseUtil = require('../utils/ResponseUtil');
const VRCE = require('../utils/ViewResultCodeEnum');
const Constant = require('../config/Constant');
const OperatorType = require('../config/OperatorType');
const globToRegExp = require('glob-to-regexp');
const HelperUtil = require('../utils/HelperUtil');
const moment = require('moment');
module.exports = (options, app) => {


    let verPath = function (path) {
        const whitelist = [
            '/MP_verify_1tS0LINY4TFkPf4X.txt',
            '*/common/*',
            '*/oauth2/authorize'
        ];
        let isWhite = false;

        for (let i = 0; i < whitelist.length; i++) {
            let re = globToRegExp(whitelist[i]);
            let ttre = re.test(path);
            if (ttre === true) {
                isWhite = true;
                break;
            }
        }

        console.log('isWhite======',isWhite)
        return isWhite;
    };

    return async function middlewarreone(ctx, next) {

        let logBody = null;
        if (ctx.request.body) {
            logBody = JSON.parse(JSON.stringify(ctx.request.body));
            delete logBody.newPassword;
            delete logBody.oldPassword;
            delete logBody.password;
        }
        console.log(moment().format('YYYY-MM-DD HH:mm:ss'),ctx.method,ctx.path, logBody, ctx.query, ctx.params);
        ctx.app.logger.info(ctx.method,ctx.path, logBody, ctx.query, ctx.params);

        let loginInfo = ctx.getLoginInfo();
        let body = ctx.request.body;
        if (body) {
            body = JSON.parse(JSON.stringify(ctx.request.body));
            delete body.newPassword;
            delete body.oldPassword;
            delete body.password;
        }

        const operLogParams = {
            operSource: 'API',
            requestMethod: ctx.method.toUpperCase(),
            operatorType: loginInfo.operatorType,
            operatorId: loginInfo.operatorId,
            operatorName: loginInfo.createBy,
            operUrl: ctx.path,
            operIp: ctx.getIP(),
            operLocation: ctx.getIpLocal(),
            operParansArgs: ctx.params ? HelperUtil.createCipher(JSON.stringify(ctx.params)) : ctx.params,
            operQueryArgs: ctx.query ? HelperUtil.createCipher(JSON.stringify(ctx.query)) : ctx.query,
            operBodyArgs: ctx.request.body ? HelperUtil.createCipher(JSON.stringify(body)) : ctx.request.body
        };
        ctx.service.sysOperLog.insertSelective(operLogParams);


        if (verPath(ctx.path)) {
            console.log(`white path:${ctx.path}`);
            let user_token = ctx.get('Authorization');
            let resultToken = await ctx.verifyToken(user_token);
            if (resultToken) {
                let redUser = await ctx.service.redis.get(Constant.LOGIN_TOKEN_KEY + resultToken.login_user_key);
                if(redUser && Number(redUser.expireTime) > new Date().getTime()){
                    if (ctx.request == null) {
                        ctx.request = {}
                    }
                    if (ctx.request.body == null) {
                        ctx.request.body = {};
                    }
                    if (redUser.type === OperatorType.APP_WECHAT) {
                        ctx.request.body.sessionUserId = redUser.userId;
                    }
                    redUser.email = resultToken.email;
                    redUser.name = resultToken.name;
                    ctx.request.body.tokenUserInfo = redUser;
                }
            }

            await next();
            return
        }
        let user_token = ctx.get('Authorization');
        console.log('user_token===',user_token)
        let resultToken = await ctx.verifyToken(user_token);
        if (!resultToken) {
            console.error(`请求访问：${ctx.path}，认证失败，无法访问系统资源`);
            ctx.app.logger.error(`请求访问：${ctx.path}，认证失败，无法访问系统资源`);
            return ctx.body = ResponseUtil.resError(VRCE.ERROR401[1], VRCE.ERROR401[0])
        }
        let redUser = await ctx.service.redis.get(Constant.LOGIN_TOKEN_KEY + resultToken.login_user_key);
        if (!redUser) {
            console.error(`请求访问：${ctx.path}，认证失败，无法访问系统资源`);
            ctx.app.logger.error(`请求访问：${ctx.path}，认证失败，无法访问系统资源`);
            return ctx.body = ResponseUtil.resError(VRCE.ERROR401[1], VRCE.ERROR401[0])
        }
        if (Number(redUser.expireTime) < new Date().getTime()) {
            console.error(`请求访问：${ctx.path}，认证失败，无法访问系统资源`);
            ctx.app.logger.error(`请求访问：${ctx.path}，认证失败，无法访问系统资源`);
            return ctx.body = ResponseUtil.resError(VRCE.ERROR401[1], VRCE.ERROR401[0])
        }
        await ctx.refreshToken(resultToken.login_user_key);
        if (ctx.request == null) {
            ctx.request = {}
        }
        if (ctx.request.body == null) {
            ctx.request.body = {};
        }
        if (redUser.type === OperatorType.APP_WECHAT) {
            ctx.request.body.sessionUserId = redUser.userId;
        }

        redUser.email = resultToken.email;
        redUser.name = resultToken.name;
        ctx.request.body.tokenUserInfo = redUser;
        await next();
    }
};
